import Mock from 'mockjs'
import * as sysMenu from './menu'

// tips
// 1. 开启/关闭[业务模块]拦截, 通过调用fnCreate方法[isOpen参数]设置.
// 2. 开启/关闭[业务模块中某个请求]拦截, 通过函数返回对象中的[isOpen属性]设置.
fnCreate(sysMenu, true)

/**
 * 创建mock模拟数据
 * @param {*} mod 模块
 * @param {*} isOpen 是否开启?
 */
function fnCreate (mod, isOpen = true) {
  if (isOpen) {
    for (var key in mod) {
      ((res) => {
        if (res.isOpen !== false) {
          Mock.mock(new RegExp(res.url + ".*"), res.type, (opts) => {
            let data = res.data(getQueryVariable(opts.url,''))
            console.log('%cmock拦截, 请求: ', 'color:blue', opts)
            console.log('%cmock拦截, 响应: ', 'color:blue', data)
            return data
          })
        }
      })(mod[key]() || {})
    }
  }
}

/**
 * 获取url参数
 * @param variable
 * @returns {string|boolean}
 */
function getQueryVariable(url,variable)
{
  let num = url.indexOf('?')
  let query = url.substr(num+1)
  let vars = query.split("&")
  for (var i=0;i<vars.length;i++) {
    var all = {}
    var pair = vars[i].split("=")
    if(pair[0] == variable){return pair[1]}
    all[pair[0]] = pair[1]
  }
  return all
}
